package com.qwt.part_time_api.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qwt.part_time_api.error.BusinessException;
import com.qwt.part_time_api.error.ErrorCode;
import com.qwt.part_time_api.vo.params.CodeParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Tzeao
 * 邮箱验证码
 */
@Slf4j
@Component
public class EmailUtils {

    @Autowired
    JavaMailSender mailSender;
    @Resource
    RedisTemplate<String, String> redisTemplate;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 生成验证码,并给接收的邮箱发送邮件
     */
    public boolean sendCode(CodeParams params) {
        log.info("获取验证码");
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            //生成随机数
            String code = randomCode();
            //存入redis 时间60秒
            redisTemplate.opsForValue().set("QWT-CODE_" + params.getEmail(), code, 60, TimeUnit.SECONDS);
            //发送方的邮箱地址，而不是接收方的邮箱地址
            messageHelper.setFrom(from);
            // 接收方的邮箱地址
            messageHelper.setTo(params.getEmail());
            // 邮箱标题
            messageHelper.setSubject("凤栖梧桐校园兼职管理平台");
            String html = "<head>\n" +
                    "    <base target=\"_blank\" />\n" +
                    "    <style type=\"text/css\">::-webkit-scrollbar{ display: none; }</style>\n" +
                    "    <style id=\"cloudAttachStyle\" type=\"text/css\">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>\n" +
                    "    <style id=\"blockquoteStyle\" type=\"text/css\">blockquote{display:none;}</style>\n" +
                    "    <style type=\"text/css\">\n" +
                    "        body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}\n" +
                    "        td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}\n" +
                    "        pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}\n" +
                    "        th,td{font-family:arial,verdana,sans-serif;line-height:1.666}\n" +
                    "        img{ border:0}\n" +
                    "        header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}\n" +
                    "        blockquote{margin-right:0px}\n" +
                    "    </style>\n" +
                    "</head>\n" +
                    "<body tabindex=\"0\" role=\"listitem\">\n" +
                    "<table width=\"700\" border=\"0\" align=\"center\" cellspacing=\"0\" style=\"width:700px;\">\n" +
                    "    <tbody>\n" +
                    "    <tr>\n" +
                    "        <td>\n" +
                    "            <div style=\"width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;\">\n" +
                    "                <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"700\" height=\"39\" style=\"font:12px Tahoma, Arial, 宋体;\">\n" +
                    "                    <tbody><tr><td width=\"210\"></td></tr></tbody>\n" +
                    "                </table>\n" +
                    "            </div>\n" +
                    "            <div style=\"width:680px;padding:0 10px;margin:0 auto;\">\n" +
                    "                <div style=\"line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;\">\n" +
                    "                    <strong style=\"display:block;margin-bottom:15px;\">尊敬的用户：<span style=\"color:#f60;font-size: 16px;\"></span>您好！</strong>\n" +
                    "                    <strong style=\"display:block;margin-bottom:15px;\">\n" +
                    "                        您正在进行 <span style=\"color: red\"> " + params.getInfo() + " </span>操作，请在验证码输入框中输入： <span style=\"color:#f60;font-size: 24px\"> " + code + "</span>，以完成操作。\n" +
                    "                    </strong>\n" +
                    "                </div>\n" +
                    "                <div style=\"margin-bottom:30px;\">\n" +
                    "                    <small style=\"display:block;margin-bottom:20px;font-size:12px;\">\n" +
                    "                        <p style=\"color:#747474;\">\n" +
                    "                            注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证帐户安全\n" +
                    "                            <br>（工作人员不会向你索取此验证码，请勿泄漏！)\n" +
                    "                        </p>\n" +
                    "                    </small>\n" +
                    "                </div>\n" +
                    "            </div>\n" +
                    "            <div style=\"width:700px;margin:0 auto;\">\n" +
                    "                <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
                    "                    <p>此为系统邮件，请勿回复<br>\n" +
                    "                        请保管好您的邮箱，避免账号被他人盗用\n" +
                    "                    </p>\n" +
                    "                    <b>凤栖梧桐工作团队</b>\n" +
                    "                </div>\n" +
                    "            </div>\n" +
                    "        </td>\n" +
                    "    </tr>\n" +
                    "    </tbody>\n" +
                    "</table>\n" +
                    "</body>";
            // 邮箱内容
            messageHelper.setText(html, true);
            // 发送邮箱
            mailSender.send(message);
            log.info("发送成功");
            return true;
        } catch (Exception e) {
            log.info("发送失败：{}", e.getMessage());
            return false;
        }
    }
    // TODO 防止多用户同时访问时 数据同时更新的情况出现
    // TODO 使用本地线程 减少重复查询数据库

    /**
     * 随机生成6位数的验证码
     *
     * @return String code
     */
    public String randomCode() {
        int rand = 6;
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < rand; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 检验验证码是否一致
     */
    public boolean checkCode(CodeParams params) throws BusinessException {
        log.info("校验验证码");
        String s = redisTemplate.opsForValue().get("QWT-CODE_" + params.getEmail());
        if (StringUtils.isEmpty(params.getCode())) {
            log.info("验证码为空");
            throw new BusinessException(ErrorCode.ERR_CODE_NULL);
        }

        if (StringUtils.isEmpty(s)) {
            log.info("验证码过期");
            throw new BusinessException(ErrorCode.ERR_CODE_OUT);
        }

        int length = 6;
        if (!(params.getCode().length() == length)) {
            log.info("验证码长度不符合规范");
            throw new BusinessException(ErrorCode.ERR_CODE_LENGTH);
        }

        if (!(StringUtils.equals(s, params.getCode()))) {
            log.info("验证码不正确");
            throw new BusinessException(ErrorCode.ERR_CODE_WRONG);
        }
        log.info("校验成功");
        // 验证成功 删除redis里面的验证码
        redisTemplate.delete("QWT-CODE_" + params.getEmail());
        return true;
    }
}

